package Servlet;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.swing.text.Style;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/yanzhengma")
public class yanzhengma extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        int width=100;//单位像素
        int height=80;//单位像素
                //1.创建BufferedImage对象
        BufferedImage bufferedImage=new BufferedImage
                (width,height,BufferedImage.TYPE_INT_RGB);
      //2美化
        //得到渲染的对象
        Graphics g=bufferedImage.getGraphics();
//设置背景色
        g.setColor(new Color(190,60,100));
        //画笔进行填充背景色
        g.fillRect(0,0,width,height);
        //准备往里面赛字符
        //设置字符
        String s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random r=new Random();
        int red=r.nextInt(150);
        int green=r.nextInt(150);
        int blue=r.nextInt(150);
        //随机生成
        for (int i=0;i<=4;i++){
            //取角标
            int index= r.nextInt(s.length());
            //获取字符串里的字符
            char c = s.charAt(index);
            g.setFont(new Font("楷体",Font.BOLD,30));
            g.setColor(new Color(red,green,blue));
            //获取的字符写进图片
            g.drawString(c+"",width/5*i,height/2);
        }
        //干扰线
        //两点成线
        for (int i = 0; i <5 ; i++) {
            int x1 = r.nextInt(width);
            int y1 = r.nextInt(height);
            int x2 = r.nextInt(width);
            int y2 = r.nextInt(height);
            g.setColor(Color.blue);
            g.drawLine(x1,x2,y1,y2);

        }
        //3响应到浏览器来显示
        ImageIO.write(bufferedImage,
                "jpeg",
                response.getOutputStream());

    }
}
